<template>
	<div class="maker-setup-manager">
		<div class="main_content">
			<div class="main_content_title">
				<div class="left">
					<template v-for="(item, index) in $route.meta.title">
						<span v-if="languageId === item.langId">{{ item.name }}</span>
					</template>
				</div>
				<div class="right" />
			</div>
			<div class="main_content_con">
				<!-- 语言动态标签页面 -->
				<el-row :gutter="24">
					<el-col :span="20">
						<elTabPane :isShow="isTag" :tagId="tagId" @tagClick="tagClick"></elTabPane>
					</el-col>
				</el-row>
				<el-form ref="info" :model="info" :rules="rules" class="demo-ruleForm">
					<el-form v-for="(info, index) in info.list" :ref="`info${index}`" :model="info" :rules="rules"
						v-show="tagId === info.langId" :key="index" label-width="auto" class="demo-ruleForm">
						<div class="content_info">
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.isStartMaker')" prop="isDistribution">
										<el-radio-group v-model="info.isDistribution"
											@change="copyValue('list', 'isDistribution', info.isDistribution)">
											<el-radio :label=1>{{ $t('publicBtn.open') }}</el-radio>
											<el-radio :label=2>{{ $t('publicBtn.close') }}</el-radio>
										</el-radio-group>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.disLevelSet')" prop="distributionLevel">
										<el-input v-model="info.distributionLevel" type="number" :placeholder="$t('placeholderTip.enter')"
											@change="copyValue('list', 'distributionLevel', info.distributionLevel)" />
									</el-form-item>
								</el-col>
								<el-col :span="16" style="display: flex;justify-content: flex-start;align-items: center;">
									<el-button type="primary" @click="getSet(info.distributionLevel)">{{
										$t('el.popconfirm.confirmButtonText') }}</el-button>
									<div style="margin-left: 20px;font-size:14px">{{ $t('text.disLevelSetTip') }}</div>
								</el-col>
							</el-row>
							<div class="title">
								<span style="font-size:14px;color:#606266;font-weight:bold">{{ $t('formLabel.commissionSetUp') }}</span>
								<span style="margin-left:22px;font-size:14px;color:#606266;">{{ $t('text.commissionSetTip') }}</span>
							</div>
							<el-row :gutter="24">
								<el-col :span="22">
									<el-table style="margin-top:22px;" :data="info.levels" border>
										<el-table-column :label="$t('formLabel.sort')" prop="sort" align="center" width="80px" />
										<el-table-column :label="$t('formLabel.disLevel')" align="center">
											<template slot-scope="scope">
												<template v-for="(level, index2) in $t('distributionLevel')">
													<span v-if="scope.$index === index2">{{ level }}</span>
												</template>
											</template>
										</el-table-column>
										<el-table-column :label="$t('formLabel.enterStore')" align="center">
											<template slot-scope="scope">
												<el-form-item label=" " label-width="2px" :prop="'levels.' + scope.$index + '.comeKickback'"
													:rules="rules.comeKickback">
													<el-input v-model="scope.row.comeKickback" :placeholder="$t('placeholderTip.enter')"
														@change="getCopyValue(scope.$index, scope.row.comeKickback, 'comeKickback')"
														style="width:95%">
														<template slot="append">{{ $t('text.priceDollar') }}</template>
													</el-input>
												</el-form-item>
											</template>
										</el-table-column>
										<el-table-column :label="$t('formLabel.bookCar')" align="center">
											<template slot-scope="scope">
												<el-form-item label=" " label-width="2px" :prop="'levels.' + scope.$index + '.reserveKickback'"
													:rules="rules.reserveKickback">
													<el-input v-model="scope.row.reserveKickback" :placeholder="$t('placeholderTip.enter')"
														@change="getCopyValue(scope.$index, scope.row.reserveKickback, 'reserveKickback')"
														style="width:95%">
														<template slot="append">{{ $t('text.priceDollar') }}</template>
													</el-input>
												</el-form-item>
											</template>
										</el-table-column>
										<el-table-column :label="$t('formLabel.buyCar')" align="center">
											<template slot-scope="scope">
												<el-form-item label=" " label-width="2px" :prop="'levels.' + scope.$index + '.deliveryKickback'"
													:rules="rules.deliveryKickback">
													<el-input v-model="scope.row.deliveryKickback" :placeholder="$t('placeholderTip.enter')"
														@change="getCopyValue(scope.$index, scope.row.deliveryKickback, 'deliveryKickback')"
														style="width:95%">
														<template slot="append">{{ $t('text.priceDollar') }}</template>
													</el-input>
												</el-form-item>
											</template>
										</el-table-column>
									</el-table>
								</el-col>
							</el-row>
							<el-row :gutter="24" style="margin-top:22px">
								<el-col :span="24">
									<el-form-item :label="$t('formLabel.homeBanner')" prop="indexImg">
										<div class="boxIgmContent">
											<div class="imgBox" v-for="(img, index1) in info.indexImg" :key="index1">
												<upload-imgs customsrc="true" :defsrc="img"
													:on-success="function (res, file) { return handleAvatarSuccess(res, file, info, 'indexImg', 'more', index1) }">
													<i class="el-icon-plus avatar-uploader-icon" />
												</upload-imgs>
												<div v-if="img" class="deleteImg" @click.stop="deleteImg(info, 'indexImg', index1)">
													<img src="@/assets/images/close.png">
												</div>
											</div>
											<div class="avatar-uploader" v-if="info.indexImg.length < limit">
												<upload-imgs customsrc="true" :imgmums="info.indexImg.length"
													:on-success="function (res, file) { return handleAvatarSuccess(res, file, info, 'indexImg', 'more') }">
													<i class="el-icon-plus avatar-uploader-icon" />
												</upload-imgs>
											</div>
											<div class="tipInfo">（{{ $t('text.size') }}750*260px）</div>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24" style="margin-top:22px">
								<el-col :span="24">
									<el-form-item :label="$t('formLabel.makerBanner')" prop="makerImg">
										<div class="boxIgmContent">
											<div class="imgBox" v-for="(img, index1) in info.makerImg" :key="index1">
												<upload-imgs customsrc="true" :defsrc="img"
													:on-success="function (res, file) { return handleAvatarSuccess(res, file, info, 'makerImg', 'more', index1) }">
													<i class="el-icon-plus avatar-uploader-icon" />
												</upload-imgs>
												<div v-if="img" class="deleteImg" @click.stop="deleteImg(info, 'makerImg', index1)">
													<img src="@/assets/images/close.png">
												</div>
											</div>
											<div class="avatar-uploader" v-if="info.makerImg.length < limit">
												<upload-imgs customsrc="true" :imgmums="info.makerImg.length"
													:on-success="function (res, file) { return handleAvatarSuccess(res, file, info, 'makerImg', 'more') }">
													<i class="el-icon-plus avatar-uploader-icon" />
												</upload-imgs>
											</div>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="22">
									<el-form-item :label="$t('formLabel.makerRules')" prop="makerRule">
										<Tinymce :content="info.makerRule"
											:on-message="function (res) { return messageInfo(res, info, 'makerRule') }" :settingData="setting"
											height="500"></Tinymce>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-form>
				<div class="footerBtn">
					<el-button v-if="propUpType !== 'detail'" type="primary" @click="addSubmitForm"
						v-loading.fullscreen.lock="fullscreenLoading">{{ $t('el.popconfirm.confirmButtonText') }}</el-button>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import {
	getMakerConfigInfo,
	setMakerConfigUpdate,
} from '@/api/maker-setup'
import UploadImgSimple from '@/components/Upload/UploadImgSimple'
import UploadImgSimples from '@/components/Upload/UploadImgSimple_more'
import elTabPane from '@/components/el-tab-pane/index'; //语言动态标签页面
import defaultSettings from '@/settings'
import Tinymce from '@/components/VueTinymceUeditor/index.vue'
export default {
	name: 'MakerSetupManager',
	components: {
		Tinymce,
		elTabPane,
		UploadImg: UploadImgSimple,
		UploadImgs: UploadImgSimples //多张图片
	},
	data() {
		return {
			tagId: '',//语言id 默认id 
			isTag: false,
			BASE_IMG: defaultSettings.BASE_IMG,
			limit: 5,
			info: {
				list: []
			},
			rules: {
				makerRule: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
				],
				distributionLevel: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
					{
						required: false,
						pattern: /^[0-9\.]+$/,
						message: this.$t('text.isNumber'),
						trigger: 'blur'
					}
				],
				indexImg: [
					{
						required: true,
						message: this.$t('placeholderTip.pUpload'),
						trigger: 'change'
					}
				],
				makerImg: [
					{
						required: true,
						message: this.$t('placeholderTip.pUpload'),
						trigger: 'change'
					}
				],
				comeKickback: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
				],
				reserveKickback: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
				],
				deliveryKickback: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
				],
			},
			countryList: [], // 省列表
			oblastList: [], // 市列表
			cityList: [], // 区列表
			propUpType: '', // 'add' edit detail
			setting: {
				menubar: true, // //是否显示菜单栏
				branding: true, //取消tinymce水印
				paste_word_valid_elements: '*[*]', //word粘贴使用
				paste_data_images: true, //// 默认是false的，记得要改为true才能粘贴
				images_file_types: 'jpeg,jpg,png,gif',
				toolbar_drawer: 'sliding', //工具栏过多，点击“...”打开抽屉过度效果
				plugins: [
					'lists',
					'code',
					'table',
					'formatselect',
					'colorpicker',
					'textcolor',
					'contextmenu',
					'preview',
					'fullscreen',
					'media',
					'link',
					'image',
					'paste'
				],
				toolbar:
					'undo redo | fullscreen | alignleft aligncenter alignright alignjustify |indent_use_margin bullist | image media table | styleselect | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | superscript subscript | removeformat | paste|'
			},
			fullscreenLoading: false,
		}
	},
	computed: {
		languageId() {
			// 固定语种ID  1:中文  2:英文 3:俄文 4:乌语
			return this.$store.getters.languageId
		},
		languageList() {
			return this.$store.getters.languageList.length > 0 ? this.$store.getters.languageList : JSON.parse(localStorage.getItem('languageList'))
		}
	},
	watch: {},
	mounted() {
		window._vm = this
		this.propUpType = this.$route.query.propUpType
		this.isTag = true;
		this.tagId = this.languageId;
		this.addData()
	},
	created() {
	},
	activated() {

	},

	destroyed() {
	},
	methods: {
		messageInfo(content, tar, key) {
			tar[key] = content
		},
		// 语言菜单处理
		tagClick(id) {
			if (id !== this.tagId) {
				this.resetForm('info', 2)
				this.tagId = id
			}
		},
		addData() {
			var arr = []
			this.languageList.map(i => {
				var obj = {
					langId: i.id,
					isDistribution: 1,//开启
					distributionLevel: '',//等级设置
					indexImg: [], //首页banner
					makerImg: [], //创客banner
					makerRule: '',//创客规则
					levels: []
				}
				arr.push(obj)
			})
			this.info.list = arr
			this.getInfo()

		},
		// 重置表单
		resetForm(vaid, type) {
			// type 1 重置表单 2仅清空校验
			if (this.$refs[vaid] !== undefined) {
				this.$nextTick(() => {
					Promise.all([
						//数组部分的表单，用map返回验证函数的调用
						...this.info.list.map((item, index) => {
							var refs = `info${index}`
							let valiForm = this.$refs?.[refs].validate
								? this.$refs?.[refs]
								: this.$refs?.[refs][0];
							if (type === 1) {
								valiForm.resetFields()
							} else {
								valiForm.clearValidate()
							}
						})

					])
				})

			}
		},
		// 分销等级设置
		getSet(value) {
			if (Number(value) >= 0) {
				var arr = []
				for (var u = 1; u <= value; u++) {
					var obj = {
						sort: u,
						comeKickback: '', //进店
						reserveKickback: '',//订车
						deliveryKickback: '',//购车
					}
					arr.push(obj)
				}
				this.info.list.map(i => {
					i.levels = arr
				})
			} else {
				this.$message({
					showClose: true,
					message: this.$t('text.isNumber'),
					type: 'success'
				})
			}
		},
		// 佣金设置表格 非多语言字段数据处理
		getCopyValue(index, value, key) {
			var list = this.info.list
			list.map(i => {
				var arr = JSON.parse(JSON.stringify(i.levels))
				arr[index][key] = value
				i.levels = arr
			})
			this.info.list = list
		},

		// 无多语言字段处理
		copyValue(key, key2, value) {
			this.info[key].map(i => {
				i[key2] = value
			})
		},
		deleteImg(tar, key, index) {
			//多张图片删除处理
			if (index >= 0) {
				// 多语言
				tar[key].splice(index, 1)
			}
			this.$forceUpdate()
		},
		handleAvatarSuccess(res, file, tar, key, type, index) {
			if (res) {
				//多张图片处理 
				if (type === 'more') {
					if (index >= 0) {
						// 多语言图片
						tar[key][index] = res.key
					} else {
						// 多语言图片
						tar[key].push(res.key)
					}
				}
				this.$forceUpdate()
			}
		},
		getCheck(index) {
			var list = JSON.parse(JSON.stringify(this.info.list))
			list.splice(index, 1)
			var falg1 = []
			for (var i = 0; i < list.length; i++) {
				var item = list[i]
				// 表单校验
				var name = ''
				// 多语言必填字段
				if (item.indexImg[0] && item.makerImg[0] && item.makerRule) {
					// 多语言必填字段 + 非必填多语言字段
				} else if (item.indexImg[0] || item.makerImg[0] || item.makerRule) {
					this.languageList.map(j => {
						if (j.id === item.langId) {
							name = j.name
						}
					})
					this.$message({
						showClose: true,
						message: name + ':' + this.$t('text.improveForms'),
						type: 'warning'
					})
					falg1.push(0)
					return false
				} else {
					falg1.push(1)
				}
			}
			var isallZeros = false
			// 判断是否包含0
			if (falg1.length > 0) {
				isallZeros = falg1.includes(0)
			}
			return !isallZeros
		},
		// 提交
		addSubmitForm() {
			var list = JSON.parse(JSON.stringify(this.info.list))
			var flag = false
			for (var i = 0; i < list.length; i++) {
				var item = list[i]
				var index = i
				// 当前语种 表单校验every
				if (this.tagId === item.langId) {
					let valiForm = this.$refs?.[`info${index}`].validate
						? this.$refs?.[`info${index}`]
						: this.$refs?.[`info${index}`][0];
					valiForm.validate((res) => {
						if (res) {
							// flag = true // 一个多语言字段 直接校验当前表单 
							flag = this.getCheck(index) //多个多语言 需要校验其他语种表单
						} else {
							return false
						}
					})
				}
			}
			if (flag) {
				// 全部表单验证通过
				var arr = JSON.parse(JSON.stringify(this.info.list))
				arr.map(i => {
					i.indexImg = i.indexImg.toString()
					i.makerImg = i.makerImg.toString()
					if (i.levels.length > 0) {
						i.levels.map(j => {
							j['level'] = j.sort //添加字段levle
							delete j.sort //删除so
						})
					}
				})
				this.fullscreenLoading = true
				setMakerConfigUpdate({
					t: arr
				})
					.then(res => {
						if (res.code === 200) {
							this.$message({
								showClose: true,
								message: this.$t('text.editSucceedTip'),
								type: 'success'
							})
							this.fullscreenLoading = false
							this.getInfo()
						}
					})
					.finally(() => {
						this.fullscreenLoading = false
					})
			}
		},
		// 详情
		getInfo() {
			const loading = this.$loading({
				lock: true,
				text: this.$t('text.loading'),
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			getMakerConfigInfo().then(res => {
				if (res.code === 200) {
					var arr = res.data.t || []
					if (arr.length > 0) {
						// 替换字段level === sort 替换
						this.$nextTick(() => {
							arr.map(i => {
								if (i.levels) {
									i.levels.map(j => {
										j['sort'] = j.level
										delete j.level
									})
								}
							})
						})
						this.setInfoData(arr)
					}
					loading.close()
				}
			}).catch(() => {
				loading.close()
			})
		},

		// 详情数据处理
		setInfoData(data) {
			var newArr = []
			var arr = data
			var obj = arr[0]
			if (data.length > 0) {
				this.languageList.map(i => {
					var obj_1 = {
						langId: i.id,
						isDistribution: obj.isDistribution,//开启
						distributionLevel: obj.distributionLevel,//等级设置
						indexImg: [], //首页banner ----多语言字段
						makerImg: [], //首页banner ----多语言字段
						makerRule: '',//创客规则 ----多语言字段
					}
					newArr.push(obj_1)
				})
			} else {
				this.languageList.map(i => {
					var obj = {
						langId: i.id,
						isDistribution: 1,//开启
						distributionLevel: '',//等级设置
						indexImg: [], //首页banner
						makerImg: [], //创客banner
						makerRule: '',//创客规则
						levels: []
					}
					newArr.push(obj)
				})
			}
			arr.map(j => {
				// 多语言图片数组处理
				if (j.indexImg) {
					j.indexImg = j.indexImg.split(',')
				} else {
					j.indexImg = []
				}
				if (j.makerImg) {
					j.makerImg = j.makerImg.split(',')
				} else {
					j.makerImg = []
				}
				// 根据id进行对象替换
				let index = newArr.findIndex(e =>
					e.langId == j.langId
				)
				if (index > -1) {
					// 替换对象
					newArr[index] = j
				}
			})
			this.info.list = newArr
		}
	}
}
</script>
<style lang="scss" scoped>
.maker-setup-manager {
	height: 100%;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;

	&>.main_content {
		width: 99.9%;
		height: 100%;

		&>.main_content_title {
			margin-bottom: 10px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		.main_content_con {
			height: calc(100% - 40px);
			width: 100%;
			display: inline-block;
			border: 1px solid #dfe6ec;
			padding: 20px;


			&>.el-form {
				width: 100%;
				height: calc(100% - 108px);
				margin-top: 20px;
				overflow: hidden;

				&>.el-form {
					width: 100%;
					height: 100%;
				}

				::v-deep .content_info {
					width: 100%;
					height: 100%;
					overflow: hidden;
					overflow-y: auto;

					.line {
						height: 1px;
						border: 1px solid #ebeef5;
					}

					.el-table {
						::v-deep th {
							line-height: 40px;
							padding: unset;
							background-color: #f2f2f2;
						}
					}
				}


			}

			.footerBtn {
				width: 100%;
				display: flex;
				justify-content: center;
				padding-top: 10px;
			}

			.cardBox {
				width: 104px;
				height: auto;
				float: left;
				position: relative;

				&>.name {
					text-align: center;
					color: #999;
					font-size: 12px;
				}
			}

			.el-button:hover,
			.el-button:focus {
				color: #000;
			}
		}
	}
}
</style>

